﻿using HelperLibrary;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;

namespace AVCJobDispatcherLinux.TaskJobEngine
{
    public class TaskJobManager
    {
        public static List<JobInfo> JobList = new List<JobInfo>();
        private static readonly object _locker = new object();

        public static void AddJobInfo(JobInfo jobInfo)
        {
            lock (_locker)
            {
                JobInfo existedJob = JobList.FirstOrDefault(j => j.Id == jobInfo.Id);
                if (existedJob != null)
                {
                    JobList.Remove(existedJob);
                }
                JobList.Add(jobInfo);
            }
        }

        //启动任务
        public static async void Start(IConfigurationRoot configuration)
        {
            List<SysJob> sysJobArr = new List<SysJob>();
            configuration.GetSection("SysJobArr").Bind(sysJobArr);
            foreach (SysJob sysJob in sysJobArr)
            {
                if (!sysJob.IsDispatch)
                {
                    continue;
                }
                foreach (JobInfo jobInfo in sysJob.TaskJobs)
                { 
                    jobInfo.ExecuteUrl = $"{sysJob.ServerHost}{jobInfo.ExecuteUrl}";
                }
                JobList.AddRange(sysJob.TaskJobs);
            }

            if (JobList.Any())
            {
                foreach (var configJob in JobList)
                {
                    LogHelper.LogDebug($"Add job: {configJob.ExecuteUrl}");
                    await Worker.ExecuteFixedJobAsync<TaskJob>(configJob);
                }
            }
        }
    }
}
